package com.example.boot1.conttoller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
public class ImgController {

    @Autowired
    private ResourceLoader resourceLoader;

    @GetMapping("/image/{filename}")
    public ResponseEntity<?> getImage(@PathVariable String filename) throws Exception {
        // 获取图片路径
        Resource image = resourceLoader.getResource("classpath:/static/tempimg/" + filename);

        BufferedImage imageB = ImageIO.read(image.getInputStream());
        byte[] bytes = convertToBytes(imageB);
        HttpHeaders headers = new HttpHeaders();

        // 设置ContentType为图片格式（根据需要修改）
        headers.setContentType(MediaType.IMAGE_JPEG);

        return ResponseEntity.ok().headers(headers).body(bytes);

    }
    private static byte[] convertToBytes(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", baos);
        return baos.toByteArray();
    }

}

